package cn.sh.tools.util.file;

import cn.sh.tools.domain.constant.CommonConstant;
import cn.sh.tools.service.component.mail.MailComponent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author shihao
 * @description 文件监听
 */
@Component
@Slf4j
public class FileMonitor {

    private FileAlterationMonitor fileMonitor;

    /**
     * 邮件组件
     */
    @Resource
    private MailComponent mailComponent;

//    @PostConstruct
    private void init() {
        // TODO 文件路径不对，加载不到。
        FileAlterationObserver observer = new FileAlterationObserver(CommonConstant.MAIL_INFO,
                FileFilterUtils.and(FileFilterUtils.fileFileFilter(),
                        FileFilterUtils.suffixFileFilter("dd")));

        FileListener fileListener = new FileListener();
        observer.addListener(fileListener);

        this.fileMonitor = new FileAlterationMonitor(5000, observer);
        try {
            this.fileMonitor.start();
        } catch (Exception e) {
            log.error("文件线程监控启动异常", e);
        }
    }

//    @PreDestroy
    public void destroy() {
        try {
            this.fileMonitor.stop();
        } catch (Exception e) {
            log.error("文件线程监控关闭异常", e);
        }
    }

    private class FileListener extends FileAlterationListenerAdaptor {

        @Override
        public void onFileChange(File file) {
            mailComponent.init();
        }

    }

}
